package com.nuoniu.sibanyun.service.cm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.controller.cm.CmContractChange;
import com.nuoniu.sibanyun.entity.cm.CmContract;
import com.nuoniu.sibanyun.entity.cm.ContractType;
import com.nuoniu.sibanyun.entity.erp.ErpNumberSet;
import com.nuoniu.sibanyun.mapper.cm.CmContractMapper;
import com.nuoniu.sibanyun.service.cm.*;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpNumberSetService;
import com.nuoniu.sibanyun.service.finance.IVReceivePaymentPlanService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 合同管理主表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-10-21
 */
@Service
public class CmContractServiceImpl extends ServiceImpl<CmContractMapper, CmContract> implements ICmContractService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IContractTypeService typeService;
    @Autowired
    private IErpNumberSetService numberSetService;
    @Autowired
    private ICmContractSubjectService subjectService;
    @Autowired
    private ICmContractFileService fileService;
    @Autowired
    private ICmContractClauseService clauseService;
    @Autowired
    private IVReceivePaymentPlanService planService;
    @Autowired
    private ICmContractChangeService changeService;

    @Override
    @Transactional
    public void saveContract(CmContract contract) {
        UserInfo userInfo = UserThreadLocal.get();

        if(contract.getId() == null) {
            contract.setCompanyId(userInfo.getCompanyId());
            contract.setCompanyName(userInfo.getCompanyName());
            contract.setAccountId(accountService.getCurrentAccountId());
            contract.setCreateUserId(userInfo.getUserId());
            contract.setCreateUserName(userInfo.getRealName());
            contract.setContractCode(getCode(contract.getContractTypeId()));
        }else {
            CmContract cmContract = this.getById(contract.getId());
            if(cmContract.getVoucherState() != 0) {
                throw new NuoNiuException("合同已审核,不能修改");
            }

            contract.setUpdateDate(LocalDateTime.now());
            contract.setUpdateUserId(userInfo.getUserId());
            contract.setUpdateUserName(userInfo.getRealName());
        }

        //保存合同主
        saveOrUpdate(contract);

        //变更存档
        List<CmContractChange> changes = changeService.getByContract(contract.getId());
        CmContractChange change = new CmContractChange();
        if(changes.size() == 0) {
            change.setContractId(contract.getId().intValue());
            change.setContractCode(contract.getContractCode());
            change.setContractName(contract.getContractName());
            change.setCompanyId(userInfo.getCompanyId());
            change.setStatus(2);
            change.setVersionCode("000");
            change.setIsInitialVersion(true);
            changeService.save(change);
        }

        //保存合同明细
        if(contract.getOrderDetailList().size() > 0) {
            List<Long> detailIds = new ArrayList<>();
            contract.getOrderDetailList().forEach(d -> {
                if(d.getId() != null) {
                    detailIds.add(d.getId());
                }else {
                    d.setOrderId(contract.getId().intValue());
                    d.setAccountId(accountService.getCurrentAccountId());
                    d.setCompanyId(userInfo.getCompanyId());
                }

                if(change.getId() != null) {
                    d.setChangeId(change.getId().intValue());
                }
            });

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("company_id", userInfo.getCompanyId());
            wrapper.eq("order_id", contract.getId());
            if(detailIds.size() > 0) {
                wrapper.notIn("id", detailIds);
            }

            subjectService.remove(wrapper);
            subjectService.saveOrUpdateBatch(contract.getOrderDetailList());
        }

        //保存收付款计划
        List<Long> pIds = new ArrayList<>();
        contract.getReceivePaymentPlans().forEach(p -> {
            if(p.getId() != null) {
                pIds.add(p.getId());
            }else {
                p.setContractId(contract.getId().intValue());
            }
        });

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("contract_id", contract.getId());
        if(pIds.size() > 0) {
            wrapper.notIn("id", pIds);
        }

        planService.remove(wrapper);
        if(contract.getReceivePaymentPlans() != null && contract.getReceivePaymentPlans().size() > 0) {
            planService.saveOrUpdateBatch(contract.getReceivePaymentPlans());
        }

        //保存条款
        if(contract.getContractClauses() != null && contract.getContractClauses().size() > 0) {
            List<Long> cIds = new ArrayList<>();
            contract.getContractClauses().forEach(c -> {
                if(c.getId() != null) {
                    cIds.add(c.getId());
                }else {
                   c.setContractId(contract.getId().intValue());
                   c.setCompanyId(userInfo.getCompanyId());
                }

                if(change.getId() != null) {
                    c.setChangeId(change.getId().intValue());
                }
            });

            QueryWrapper cWrapper = new QueryWrapper();
            cWrapper.eq("company_id", userInfo.getCompanyId());
            cWrapper.eq("contract_id", contract.getId());
            if(cIds.size() > 0) {
                cWrapper.notIn("id", cIds);
            }

            clauseService.remove(cWrapper);
            clauseService.saveOrUpdateBatch(contract.getContractClauses());
        }

        //保存附件
        List<Long> fIds = new ArrayList<>();
        contract.getContractFiles().forEach(f -> {
            if(f.getId() != null) {
                fIds.add(f.getId());
            }else {
                f.setContractId(contract.getId().intValue());
            }
        });

        QueryWrapper fWrapper = new QueryWrapper();
        fWrapper.eq("contract_id", contract.getId());
        if(fIds.size() > 0) {
            wrapper.notIn("id", fIds);
        }

        fileService.remove(fWrapper);
        if(contract.getContractFiles() != null && contract.getContractFiles().size() > 0) {
            fileService.saveOrUpdateBatch(contract.getContractFiles());
        }
    }

    @Override
    public String getCode(Integer typeId) {
        UserInfo userInfo = UserThreadLocal.get();
        ContractType type = typeService.getById(typeId);
        ErpNumberSet numberSet = numberSetService.getById(type.getNumberSetId());
        String dateStr = numberSet.getMedian() == 1 ? "%Y-%m-%d" : "%Y-%m";
        String code = baseMapper.getCode(userInfo.getCompanyId(), dateStr);
        return numberSetService.getCode(numberSet, code);
    }

    @Override
    public CmContract getDetail(Long id) {
        CmContract contract = this.getById(id);
        QueryWrapper wrapper = new QueryWrapper();
        QueryWrapper dWrapper = new QueryWrapper();
        wrapper.eq("contract_id", id);
        dWrapper.eq("order_id", id);
        contract.setContractClauses(clauseService.list(wrapper));
        contract.setContractFiles(fileService.list(wrapper));
        contract.setReceivePaymentPlans(planService.list(wrapper));
        contract.setOrderDetailList(subjectService.list(dWrapper));
        return contract;
    }

    @Override
    public void delete(Long id) {
        CmContract contract = this.getById(id);
        if(contract.getVoucherState() != 0) {
            throw new NuoNiuException("已审核,不能删除");
        }

        this.removeById(id);
    }

    @Override
    public void examine(Long id, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        CmContract contract = this.getById(id);

        if(status.equals(1)) {
            if(contract.getVoucherState().equals(0)) {
                contract.setVoucherState(status);
            }
        }else {
            if(contract.getVoucherState().equals(1)) {
                contract.setVoucherState(status);
            }
        }

        contract.setReviewerDate(LocalDate.now());
        contract.setReviewerUserId(userInfo.getUserId());
        contract.setReviewerUserName(userInfo.getRealName());
        this.updateById(contract);
    }

    @Override
    public void file(Long id) {
        CmContract contract = this.getById(id);
        if(!contract.getVoucherState().equals(1)) {
            throw new NuoNiuException("未审核");
        }

        contract.setIsFile(true);
        this.updateById(contract);
    }

    @Override
    public void close(Long id) {
        CmContract contract = this.getById(id);
        contract.setVoucherState(10);

        this.updateById(contract);
    }

    @Override
    @Transactional
    public void changeContract(CmContract cmContract) {
        //获取老版本信息
        CmContract old = getDetail(cmContract.getId());
        if(old.getVoucherState().equals(10)) {
            throw new NuoNiuException("合同已终止,不能变更");
        }

        //保存更改记录
        UserInfo userInfo = UserThreadLocal.get();
        CmContractChange change = new CmContractChange();
        change.setContractId(cmContract.getId().intValue());
        change.setContractCode(old.getContractCode());
        change.setContractName(cmContract.getContractName());
        change.setCompanyId(old.getCompanyId());
        change.setVersionCode("000");
        change.setIsInitialVersion(false);
        change.setChangeCause(cmContract.getChangeCause());
        change.setChangeUserId(userInfo.getUserId());
        change.setChangeUserName(userInfo.getRealName());
        change.setChangeDate(LocalDate.now());
        changeService.save(change);

        //合同明细存档
        old.getOrderDetailList().forEach(d -> {
            d.setOrderId(0);
        });
        subjectService.updateBatchById(old.getOrderDetailList());

        //条款存档
        if(old.getContractClauses().size() > 0) {
            old.getContractClauses().forEach(c -> {
                c.setContractId(0);
            });
        }
        clauseService.updateBatchById(old.getContractClauses());

        //保存合同
        updateContract(cmContract, change.getId());
    }

    @Override
    public List<CmContractChange> getChangeList() {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("company_id", userInfo.getCompanyId());
        return changeService.list(wrapper);
    }

    @Override
    public CmContract getChangeDetail(Integer changeId) {
        QueryWrapper wrapper = new QueryWrapper();
        CmContractChange change = changeService.getById(changeId);
        wrapper.eq("change_id",changeId);

        CmContract contract = this.getById(change.getContractId());
        contract.setChangeCause(change.getChangeCause());
        contract.setContractName(change.getContractName());
        contract.setContractClauses(clauseService.list(wrapper));
        contract.setOrderDetailList(subjectService.list(wrapper));
        return contract;
    }

    @Transactional
    public void updateContract(CmContract contract, Long changeId) {
        UserInfo userInfo = UserThreadLocal.get();
        CmContract cmContract = new CmContract();
        cmContract.setId(contract.getId());
        cmContract.setContractName(contract.getContractName());
        cmContract.setUpdateDate(LocalDateTime.now());
        cmContract.setUpdateUserId(userInfo.getUserId());
        cmContract.setUpdateUserName(userInfo.getRealName());

        //保存合同主
        updateById(cmContract);

        //保存合同明细
        if(contract.getOrderDetailList().size() > 0) {
            contract.getOrderDetailList().forEach(d -> {
                d.setId(null);
                d.setChangeId(changeId.intValue());
                d.setAccountId(accountService.getCurrentAccountId());
                d.setOrderId(contract.getId().intValue());
                d.setCompanyId(userInfo.getCompanyId());
            });

            subjectService.saveOrUpdateBatch(contract.getOrderDetailList());
        }

        //保存条款
        contract.getContractClauses().forEach(c -> {
            c.setId(null);
            c.setChangeId(changeId.intValue());
            c.setContractId(contract.getId().intValue());
            c.setCompanyId(userInfo.getCompanyId());
        });

        clauseService.saveOrUpdateBatch(contract.getContractClauses());
    }
}
